package edu.nf.relaxenjoy.common.util;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageInfo;

import java.util.List;

/**
 * @author zhu
 * @date 2024-12-16
 */
public class PageUtils {
    public static <T> PageInfo<T> getPages(Integer pageNo, Integer pageSize, List<T> list) {
        if (list == null || list.isEmpty()) {
            // 返回空的 PageInfo 对象
            return new PageInfo<>();
        }

        // 使用 PageInfo 处理分页
        // 计算开始索引
        int startIndex = (pageNo - 1) * pageSize;
        if (startIndex >= list.size()) {
            // 修正页码以不超出界限
            pageNo = (int) Math.ceil((double) list.size() / pageSize);
            startIndex = (pageNo - 1) * pageSize;
        }

        // 获取当前页的数据
        int endIndex = Math.min(startIndex + pageSize, list.size());
        List<T> pageList = list.subList(startIndex, endIndex);

        // 创建 PageInfo 对象并设置相关属性
        PageInfo<T> pageInfo = new PageInfo<>(pageList);
        pageInfo.setPageNum(pageNo);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotal(list.size());
        pageInfo.setPages((int) Math.ceil((double) list.size() / pageSize));

        return pageInfo;
    }

    /**
     * 转换为 PageInfo 对象
     */
    public static <T, E> PageInfo<T> copy(PageInfo<E> page, Class<T> targetClazz) {
        // 转换记录
        List<T> records = BeanUtil.copyToList(page.getList(), targetClazz);
        PageInfo<T> pageInfo = new PageInfo<>(records);
        pageInfo.setPageNum(page.getPageNum());
        pageInfo.setPageSize(page.getPageSize());
        pageInfo.setTotal(page.getTotal());
        pageInfo.setPages(page.getPages());
        return pageInfo;
    }

    /**
     * 转换为 PageInfo 对象
     */
    public static <T, E> PageInfo<T> copy(PageInfo<E> page, List<E> sourceList, Class<T> targetClazz) {
        // 转换记录并创建新的 PageInfo
        List<T> records = BeanUtil.copyToList(sourceList, targetClazz);
        PageInfo<T> pageInfo = new PageInfo<>(records);
        pageInfo.setPageNum(page.getPageNum());
        pageInfo.setPageSize(page.getPageSize());
        pageInfo.setTotal(page.getTotal());
        pageInfo.setPages(page.getPages());
        return pageInfo;
    }
}
